import random

from utils.image_processor import ImageProcessor
from utils.llm_api import LLMApi
from utils.minio_config import MinioConfig

import tempfile
import uuid
from PIL import Image
import os
from utils.logger import logger


class ImageTextGenerator:
    """
    处理图片生成图文内容的业务逻辑
    """

    def __init__(self):
        self.image_processor = ImageProcessor()
        self.llm_api = LLMApi()
        self.minio_config = MinioConfig()

    def generate_content(self, bucket_name: str, image_name: str) -> dict:
        """
        生成图文内容

        Args:
            bucket_name: MinIO存储桶名称
            image_name: 图片文件名

        Returns:
            dict: 包含生成内容和图片URL的字典
        """
        # 设置MinIO存储桶
        self.minio_config.set_bucket_name(bucket_name)

        # 获取图片URL
        img_url = self.minio_config.get_image_url(image_name)
        logger.info(f"获取图片URL: {img_url}")

        # 获取图片内容
        image = self.minio_config.get_image(image_name)
        # 获取图片路径
        image_path = self.get_image_path(image)

        logger.info("正在处理图像...")
        logger.info("验证临时文件是否存在:", os.path.exists(image_path))
        logger.info("文件大小:", os.path.getsize(image_path), "bytes")

        # 生成图片HTML
        img_html = f"<img src='{img_url}' alt='{image_name}' />"

        # 从图片生成文本
        pre_text = self.image_processor.generate_text_from_image(image_path)

        # 使用LLM扩写文本
        prompt = f"请用中文翻译并扩写以下内容：{pre_text}，要求2000字左右"
        news_item_content = self.llm_api.get_model_res(prompt=prompt)

        # 随机插入图片
        if isinstance(news_item_content, str) and len(news_item_content) > 2:
            insert_pos = random.randint(1, len(news_item_content) - 1)
            news_item_content = (
                news_item_content[:insert_pos]
                + img_html
                + news_item_content[insert_pos:]
            )

        return {
            "content": news_item_content,
            "image_url": img_url,
            "original_text": pre_text,
        }

    def get_image_path(self, image: Image) -> str:
        # 保存图片到本地
        image_path: str = None
        try:
            # 使用 uuid 生成唯一的临时文件名
            temp_dir = tempfile.gettempdir()
            temp_file_name = f"{uuid.uuid4().hex}.jpg"
            image_path = os.path.join(temp_dir, temp_file_name)
            logger.info("临时文件路径：" + image_path)
            # 保存图片到临时文件
            image.save(image_path)
        except Exception as e:
            logger.info(f"保存图片到临时文件失败: {e}")
        return image_path
